package com.ipan.weixin.msg.general;

import org.apache.commons.lang.StringUtils;
import org.dom4j.Document;
import org.dom4j.Element;

/**
 * 链接消息
 * 
 * @author iPan
 * @version 2013-12-23
 */
public class LinkMsg extends PlainMsg {

	/** serialVersionUID */
	private static final long serialVersionUID = -1049203485356263108L;
	
	/** 消息标题 */
	private String title;
	
	/** 消息描述 */
	private String description;
	
	/** 消息链接 */
	private String url;
	
	public LinkMsg() {
		super(TransportType.RECEIVE);
	}
	
	public LinkMsg(Document doc) {
		this();
		fromXml(doc);
	}

	public String getTitle() {
		return title;
	}

	public void setTitle(String title) {
		this.title = title;
	}

	public String getDescription() {
		return description;
	}

	public void setDescription(String description) {
		this.description = description;
	}

	public String getUrl() {
		return url;
	}

	public void setUrl(String url) {
		this.url = url;
	}

	@Override
	public void fromXml(Document doc) {
		if (doc == null) {
			return ;
		}
		
		super.fromXml(doc);
		Element root = doc.getRootElement();
		this.url = root.elementTextTrim(EL_URL);
		this.title = root.elementTextTrim(EL_TITLE);
		this.description = root.elementTextTrim(EL_DESCRIPTION);
	}

	@Override
	public String toXml(boolean nonEmpty) {
		StringBuilder buf = new StringBuilder("<xml>");
		buf.append(super.toXml(nonEmpty));
		buf.append(wrapElementHead(EL_MSG_TYPE)).append(TYPE_LINK).append(wrapElementEnd(EL_MSG_TYPE));
		if (nonEmpty) {
			if (StringUtils.isNotEmpty(this.title)) {
				buf.append(wrapElementHead(EL_TITLE)).append(this.title).append(wrapElementEnd(EL_TITLE));
			}
			if (StringUtils.isNotEmpty(this.description)) {
				buf.append(wrapElementHead(EL_DESCRIPTION)).append(this.description).append(wrapElementEnd(EL_DESCRIPTION));
			}
			if (StringUtils.isNotEmpty(this.url)) {
				buf.append(wrapElementHead(EL_URL)).append(this.url).append(wrapElementEnd(EL_URL));
			}
		} else {
			buf.append(wrapElementHead(EL_TITLE)).append(getStringValue(this.title)).append(wrapElementEnd(EL_TITLE));
			buf.append(wrapElementHead(EL_DESCRIPTION)).append(getStringValue(this.description)).append(wrapElementEnd(EL_DESCRIPTION));
			buf.append(wrapElementHead(EL_URL)).append(getStringValue(this.url)).append(wrapElementEnd(EL_URL));
		}
		return buf.append("</xml>").toString();
	}
	
}

/*---------------------------------------------
接收：
<xml>
<ToUserName><![CDATA[toUser]]></ToUserName>
<FromUserName><![CDATA[fromUser]]></FromUserName>
<CreateTime>1351776360</CreateTime>
<MsgType><![CDATA[link]]></MsgType>
<Title><![CDATA[公众平台官网链接]]></Title>
<Description><![CDATA[公众平台官网链接]]></Description>
<Url><![CDATA[url]]></Url>
<MsgId>1234567890123456</MsgId>
</xml> 
--------------------------------------------*/